// 从 LocalStorage 获取 userInfo,并获取当前用户的Id
// 检查登录状态
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
const userInfoString = isLoggedIn ? JSON.parse(localStorage.getItem('userInfo')) : null;
let userId;
if (userInfoString) {
    // 获取userId
    userId = userInfoString.userId;
    console.log('从LocalStorage获取的用户ID:', userId);
} else {
    console.log("未拿到userId")
}
//获取当前文章的postId
const postId = localStorage.getItem('currentPostId');
if (postId) {
    console.log('获取到的postId:', postId);

} else {
    console.log('未找到postId');
}
// 从 HTML 元素中获取postId，而非依赖localStorage
// const postIdElement = document.querySelector('.postId');
// const postId = postIdElement ? postIdElement.textContent : null;
// console.log(postId);
//获取当前文章的作者Id
const authorId = localStorage.getItem('authorId');
if (authorId) {
    console.log('获取到的authorId:', authorId);

} else {
    console.log('未找到authorId');
}
// //获取当前评论的currentCommentId
// const currentCommentId = localStorage.getItem('currentCommentId');
// if (currentCommentId) {
//     console.log('获取到的currentCommentId:', currentCommentId);
//
// } else {
//     console.log('未找到currentCommentId');
// }
const alert = document.querySelector('.alert');
function showAlert(message, color) {
    alert.textContent = message;
    alert.style.color = color;
    alert.style.display = 'block';
    setTimeout(() => {
        alert.style.display = 'none';
    }, 3000);
}
const pleaseLoginAndComments = document.querySelectorAll('.pleaseLoginAndComment');
if (pleaseLoginAndComments) {
    pleaseLoginAndComments.forEach((pleaseLoginAndComment) => {
        pleaseLoginAndComment.addEventListener('click', () => {
            location.href = "/user/login";
        })
    })

}

//右侧评论区
// 获取相关元素
const commentIcon = document.querySelector('.comment-icon');
const commentCounts = document.querySelectorAll('.comment-count');
const CommentWindow = document.querySelector('.Comment-window');
const rightcommentList = CommentWindow.querySelector('.comment-list');
const ViewOtherComments = document.querySelector('.View-other-comments');
const closeButton = document.querySelector('.close-button');

// 显示评论窗口
function showCommentWindow(commentWindow) {
    commentWindow.classList.toggle('active');
    document.body.classList.toggle('active');
}

// 隐藏评论窗口
function hideCommentWindow(commentWindow) {
    commentWindow.classList.remove('active');
    document.body.classList.remove('active');
}

//关闭右侧评论区
function bindOutsideClickEvent(commentWindow) {
    // 绑定点击空白处隐藏评论框的事件
    document.addEventListener('click', function (event) {
        if (!commentWindow.contains(event.target)) {
            hideCommentWindow(commentWindow);
        }
    });
    // 绑定点击关闭按钮的事件
    closeButton.addEventListener('click', () => hideCommentWindow(CommentWindow));
}

showAllCommentsEvent(commentIcon, ViewOtherComments, CommentWindow, postId);
bindOutsideClickEvent(CommentWindow);

//控制评论区的滚动条和整个页面的滚动条的出现和隐藏
const commentWindow = document.querySelector('.comment-Window');
const bodyElement = document.body;
function handleScrollbarVisibility() {
    if (!commentWindow) {
        // console.log("评论区未出现");
        return;
    }

    function showCommentScrollbar() {
        commentWindow.style.overflowY = 'auto';
        bodyElement.style.overflow = 'hidden';
    }

    function hideCommentScrollbar() {
        commentWindow.style.overflowY = 'hidden';
        bodyElement.style.overflow = 'auto';
    }

    commentWindow.addEventListener('mouseenter', showCommentScrollbar);
    commentWindow.addEventListener('mouseleave', hideCommentScrollbar);
}

handleScrollbarVisibility();

//点击"回复"出现回复框
const replyButtons = document.querySelectorAll('.reply-button');

replyButtons.forEach((button) => {
    button.addEventListener('click', function (event) {
        event.preventDefault();

        const buttomCommentItem = event.target.closest('.comment-item');
        console.log(buttomCommentItem);
        //如果获取到了所点击"回复"按钮所对应的那个item
        if (buttomCommentItem) {
            // 检查是否已经存在要添加的子元素
            const existingReplyInput = buttomCommentItem.querySelector('.Comments-bottom-myInput');
            console.log(existingReplyInput);
            if (existingReplyInput) {
                // 如果存在，删除该子元素
                buttomCommentItem.removeChild(existingReplyInput);
            } else {
                // 如果不存在，创建并添加子元素
                const newReplyInput = document.createElement('div');
                newReplyInput.classList.add('Comments-bottom-myInput');
                const userAvatar = document.createElement('img');
                userAvatar.src = '../img/p3.png';
                userAvatar.alt = '用户头像';
                userAvatar.classList.add('user-avatar');

                const inputContainer = document.createElement('div');
                inputContainer.classList.add('Comments-bottom-input');

                const textarea = document.createElement('textarea');
                textarea.placeholder = '说点什么吧...';

                const actionContainer = document.createElement('div');
                actionContainer.classList.add('Comments-bottom-action');

                const emojiButton = document.createElement('div');
                emojiButton.classList.add('Comments-bottom-emoji-button');
                emojiButton.textContent = '😊';

                const submitButton = document.createElement('button');
                submitButton.classList.add('Comments-bottom-submit');
                submitButton.textContent = '评论';

                actionContainer.appendChild(emojiButton);
                actionContainer.appendChild(submitButton);
                inputContainer.appendChild(textarea);
                inputContainer.appendChild(actionContainer);
                newReplyInput.appendChild(userAvatar);
                newReplyInput.appendChild(inputContainer);

                buttomCommentItem.appendChild(newReplyInput);
                newReplyInput.style.width = '99%';
                newReplyInput.style.marginLeft = '19px';


                //为新创建的回复框添加input事件
                commentTextBack(textarea);
            }
        } else {
            console.log("未找到对应的Comments-bottom-items元素");
        }


    });
});
//跳转至其他用户个人主页
function otherUserPage(otherUserId) {
    if (isLoggedIn) {
        location.href = `/redirectToPage/${otherUserId}`;
    } else {
        showAlert("请先登录", 'red');

    }
}
const authorAvatar = document.querySelector('.author-avatar');
authorAvatar.addEventListener('click', () => {
    console.log("准备进入他的主页");
    const avatarId = authorAvatar.dataset.userId;
    console.log(avatarId);
    otherUserPage(avatarId);
})
//如果输入框中有内容,则将"评论"两个字的背景变换

//封装函数,否则当页面中没有动态生成回复框时 去寻找submitButton,是会报错的
function commentTextBack(textarea) {
    textarea.addEventListener('input', function () {
        // console.log("1");
        const textareaLength = textarea.value.length;
        // console.log(textareaLength);
        const submitButton = textarea.parentNode.querySelector('.Comments-bottom-submit');
        if (submitButton) {
            if (textareaLength > 0) {
                // console.log(submitButton);
                submitButton.addEventListener('mouseenter', function () {
                    // console.log("以移入");
                    submitButton.style.backgroundColor = '#505050';
                })
                submitButton.addEventListener('mouseleave', function () {
                    // console.log("以移出");
                    submitButton.style.backgroundColor = '#C5C5C5';
                })
            } else {
                submitButton.addEventListener('mouseenter', function () {
                    // console.log("没字了,移入");
                    submitButton.style.backgroundColor = '#CFCFCF';
                })
                submitButton.addEventListener('mouseleave', function () {
                    // console.log("没字了,移出");
                    submitButton.style.backgroundColor = '#C5C5C5';
                })
            }
        }

    })


}

//为页面中初始存在的textarea绑定input事件
const initialTextareas = document.querySelectorAll('textarea');
if (initialTextareas) {
    initialTextareas.forEach(commentTextBack);

}

const newsLike = document.querySelector('.newsLike');
// console.log(newsLike);
const likeicon = document.querySelector('.like-icon');
const iconlike = document.querySelector('.icon-dianzan');
const likeCount = newsLike.nextElementSibling;
// 点赞功能
function handleLikeClick() {

    newsLike.addEventListener('click', function (event) {
        if (isLoggedIn) {
            // 在点击前记录当前点赞数
            const originalCount = parseInt(likeCount.textContent);
            $.ajax({
                url: '/NewsController/likepost',
                type: "post",
                data: { postId: postId },
                success: function (result) {
                    console.log(result);
                    if (result.code == 200) {
                        const newCount = result.data;
                        if (newCount > originalCount) {

                            likeicon.style.color = 'red';
                            iconlike.style.color = 'red';
                        } else {
                            // 取消点赞操作：点赞数减少
                            likeicon.style.color = '';
                            iconlike.style.color = '';
                        }
                        //点赞数更新
                        likeCount.textContent = newCount;

                    }
                },
                error: function (error) {
                    console.log(error);
                }
            })
        } else {
            showAlert("请先登录", 'red');
        }

    });

}
const favoriteIcon = document.querySelector('.icon-a-xing2_huaban1');
const favoriteText = document.querySelector('.favoriteText');
// 收藏功能
function handleFavoriteClick() {

    favoriteIcon.addEventListener('click', function () {
        if (isLoggedIn) {
            $.ajax({
                url: '/NewsController/bookmark',
                type: "post",
                data: { postId: postId },
                success: function (result) {
                    console.log("已收藏", result);

                    if (result.message == "收藏成功") {
                        favoriteIcon.style.color = '#FFC740';
                        favoriteText.textContent = '已收藏';
                        favoriteText.style.color = '#FFC740';
                    }
                    if (result.message == "取消收藏") {
                        favoriteIcon.style.color = '';
                        favoriteText.textContent = '收藏';
                        favoriteText.style.color = '';

                    }

                },
                error: function (error) {
                    console.log(error);
                }
            })
        } else {
            showAlert("请先登录", 'red')
        }

    })
}

//关注功能
const followButton = document.querySelector('.follow-button');
function handleFollowClick() {
    followButton.addEventListener('click', () => {
        if (isLoggedIn) {
            $.ajax({
                url: '/NewsController/follow',
                type: "post",
                data: { followedId: authorId },
                success: function (result) {
                    console.log(result);
                    if (result.message == "成功关注") {
                        followButton.style.backgroundColor = '#F9F9F9';
                        followButton.style.color = '#999999';
                        followButton.innerHTML = "已关注";
                    }
                    if (result.message == "取消关注") {
                        followButton.style.backgroundColor = 'red';
                        followButton.style.color = 'white';
                        followButton.innerHTML = "关注";
                    }
                },
                error: function (error) {
                    console.log(error);
                }
            })
        } else {
            showAlert("请先登录", 'red');
        }

    })

}
//转发功能
// 点击"分享",显示分享列表
const iconShare = document.querySelector('.icon-fenxiang');
const shareLists = document.querySelector('.shareLists');
const shareConfirm = document.querySelector('.share-confirm');
const userList = document.querySelector('.userList');
let timer;
let currentType = 'follow'; // 当前显示类型
// 显示分享列表
function showShareList() {
    if (isLoggedIn) {
        console.log("准备弹出");
        clearTimeout(timer);
        shareLists.style.transform = 'scale(1)';
        shareLists.style.opacity = '1';
    }

}

// 隐藏分享列表并清除选中状态
function hideShareList(shareLists) {
    clearTimeout(timer);
    console.log("准备消失");
    shareLists.style.transform = 'scale(0)';

    // 使用setTimeout确保动画完成后再清除选中状态
    timer = setTimeout(() => {
        shareLists.style.opacity = '0';

        // 清除所有复选框的选中状态
        const checkboxes = shareLists.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = false;
        });
    }, 300);
}
document.addEventListener('click', function (event) {
    if (!shareLists.contains(event.target)) {
        hideShareList(shareLists);
    }
});
// 选项卡切换处理
function handleTabClick(type) {
    let currentSharePageNum = 1;
    currentType = type;
    // 清空原有内容
    userList.innerHTML = '';
    loadUserList(type, currentSharePageNum);
}
// 加载用户列表
function loadUserList(type, currentSharePageNum) {
    if (isLoggedIn) {
        const apiUrl = type === 'follow' ? `/followed/${userId}/${currentSharePageNum}` : `/follower/${userId}/${currentSharePageNum}`; // 假设粉丝接口为fansList

        $.ajax({
            url: apiUrl,
            type: 'GET',
            data: {
                otherUserId: userId,
                pageNum: currentSharePageNum,
            },
            dataType: 'json',
            success: function (result) {
                console.log(result);
                // 渲染用户列表
                const users = result.data;
                renderUserList(users);
            },
            error: function (error) {
                console.error('加载用户列表失败:', error);
                userList.innerHTML = '<div class="error">加载失败，请重试</div>';
            }
        });
    }

}

// 渲染用户列表
// function renderUserList(users) {
//     userList.innerHTML = users.map(user => `
//         <div class="userItems">
//         <span class="share-user-Id" style="display: none">${user.userId}</span>
//             <img src="${user.avatar}" class="share-user-avatar">
//             <span class="share-user-userName">${user.userName}</span>
//             <input type="checkbox" class="check">
//         </div>
//     `).join('');
//     const userItems = userList.querySelectorAll('.userItems');
//     userItems.forEach(item => {
//         item.addEventListener('click', function () {
//             const checkboxes = userList.querySelectorAll('input[type="checkbox"]');
//             checkboxes.forEach(cb => cb.checked = false);
//             const checkbox = this.querySelector('input[type="checkbox"]');
//             checkbox.checked = true;
//         });
//     });
// }
// 添加事件监听
// iconShare.addEventListener('click', function () {
//     if (isLoggedIn) {
//         showShareList();
//     }
// });
iconShare.addEventListener('click', function (event) {
    if (isLoggedIn) {
        event.stopPropagation(); // 关键修改：阻止事件冒泡到document
        // showShareList();
    } else {
        showAlert("请先登录", 'red');
    }
});
// shareLists.addEventListener('mouseenter', showShareList);
// shareLists.addEventListener('mouseleave', hideShareList);
// iconShare.addEventListener('click', hideShareList);

if (shareConfirm) {
    shareConfirm.addEventListener('click', function () {
        const selectedItem = userList.querySelector('.userItems input:checked').parentNode;
        if (!selectedItem) {
            showAlert('请选择要转发的用户', 'red');
            return;
        }
        const forwardedId = selectedItem.querySelector('.share-user-Id').textContent;
        $.ajax({
            url: '/NewsController/sharePost',
            type: 'POST',
            data: {
                forwardedId: forwardedId,
                postId: postId
            },
            success: function (result) {
                console.log('转发成功:', result);
                showAlert('转发成功', 'green');
                const shareCount = document.querySelector('.shareCount');
                shareCount.textContent = result.data;
                hideShareList();
            },
            error: function (error) {
                console.error('转发失败:', error);
                showAlert('转发失败，请重试', 'red');
            }
        });
    });
}
// 选项卡点击事件
shareLists.querySelectorAll('.follow-fans > div').forEach(tab => {
    // 设置初始状态
    tab.classList.toggle('active', tab.classList.contains('share-follow')); // 默认选中"关注"
    tab.dataset.type = tab.classList.contains('share-follow') ? 'follow' : 'fans'; // 绑定data-type属性

    tab.addEventListener('click', function () {
        // 切换选项卡样式
        const tabs = shareLists.querySelectorAll('.follow-fans > div');
        tabs.forEach(t => t.classList.remove('active'));
        this.classList.add('active');

        // 获取当前选项卡的类型
        const type = this.dataset.type;
        console.log('切换到类型:', type);

        // 处理点击逻辑
        handleTabClick(type);
    });
});
const defaultTab = shareLists.querySelector('.share-follow');
if (defaultTab) {
    defaultTab.click();
}
// //交互
// const checks=document.querySelectorAll('.check');
// console.log(checks);
// let selectedUserId; // 用于存储选中用户的userId
// // 为所有复选框添加点击事件
// checks.forEach(check=>{
//     check.addEventListener('click', function() {
//
//         console.log("一点纪要转发的用户");
//         // 取消其他所有复选框的选中状态
//         checks.forEach(cb => {
//             if (cb !== this) {
//                 cb.checked = false;
//             }
//         });
//
//         // 更新选中的用户ID
//         selectedUserId = this.checked ? this.dataset.userId : null;
//         console.log('选中用户ID:', selectedUserId);
//     });
// });
// // 为"点击转发"按钮添加点击事件
// if (shareConfirm) {
//     shareConfirm.addEventListener('click', function() {
//         if (!selectedUserId) {
//             showAlert('请选择要转发的用户', 'red');
//             return;
//         }
//
//         // 调用后端接口
//         $.ajax({
//             url: '/NewsController/sharePost',
//             type: 'POST',
//             data: {
//                 forwardedId: selectedUserId,
//                 postId: postId
//             },
//             success: function(result) {
//                 console.log('转发成功:', result);
//                 showAlert('转发成功', 'green');
//                 // 可选：隐藏分享列表
//                 hideShareList();
//             },
//             error: function(error) {
//                 console.error('转发失败:', error);
//                 showAlert('转发失败，请重试', 'red');
//             }
//         });
//     });
// }
// 初始化函数
function init() {
    handleLikeClick();
    handleFavoriteClick();
    handleFollowClick();
}
init();
//判断用户是否已对文章进行点赞关注收藏,来调整对应图标的颜色
function postStatus(postId) {
    $.ajax({
        url: `/post/${postId}`,
        type: "GET",
        data: {
            postId: postId,
        },
        success: function (result) {
            console.log(result);
            if (result.data.bookStatus == 1) {
                favoriteIcon.style.color = '#FFC740';
                favoriteText.textContent = '已收藏';
                favoriteText.style.color = '#FFC740';
            }
            if (result.data.followStatus == 1) {
                followButton.style.backgroundColor = '#F9F9F9';
                followButton.style.color = '#999999';
                followButton.innerHTML = "已关注";
            }
            if (result.data.likeStatus == 1) {
                likeicon.style.color = 'red';
                iconlike.style.color = 'red';
            }
        },
        error: function (error) {
            console.log(error);
        }
    })
}
postStatus(postId);

//最开始的部分评论,用的是后端获取全部评论的接口,,然后渲染前四条
//不用返回页面的那个接口的原因是因为要在页面中写静态的元素,然后使用th标签渲染数据,再添加评论后有更新了评论列表,
//就会导致数据渲染重复,不能保证页面中一直有四条评论
const rightNoComments = document.querySelector('.right-no-comments');
const noComments = document.querySelector('.no-comments');
function loadInitialComments(postId) {
    $.ajax({
        url: `/NewsController/selectComment/${postId}`,
        type: 'GET',
        data: {
            postId: postId
        },
        success: function (result) {
            console.log(result);
            updateCommentLists({
                fourComments: result.data.slice(0, 4), // 前4条为首页显示的评论
                allComments: result.data
            });
            updateCommentCount(result.data.length);

            if (result.data.length == 0) {
                rightNoComments.style.display = 'block';
                noComments.style.display = 'block';
                ViewOtherComments.style.display = 'none';
            } else {
                rightNoComments.style.display = 'none';
                noComments.style.display = 'none';
                ViewOtherComments.style.display = 'block';
            }
            // setCommentLikeStatus();
        },
        error: function (error) {
            console.error('获取初始评论失败', error);
        }
    });
}
loadInitialComments(postId);


// 点击评论图标和查看全部评论的按钮以显示右侧评论区,查看全部评论
let currentPageNum = 1;
const PAGE_SIZE = 6;
let shouldShowMoreButton = false;
function showAllCommentsEvent(commentIcon, ViewOtherComments, commentWindow, postId) {
    const showHandler = (event) => {
        event.stopPropagation();
        showCommentWindow(commentWindow);
        rightcommentList.innerHTML = '';

        currentPageNum = 1;// 每次显示评论区时重置为第一页
        $.ajax({
            url: `/post/selectComment/${postId}/1`,
            type: 'GET',
            data: {
                pageNum: 1,
                postId: postId
            },
            success: function (result) {
                console.log(result);
                // if(result.data.hasMore==false){
                //     return;
                // }
                result.data.comments.forEach(function (comment) {
                    rightcommentList.innerHTML += createCommentHtml(comment, userId);
                })
                //重新绑定删除和点赞事件
                bindDeleteCommentEvents();
                LikeCommentEvents();
                setCommentLikeStatus();
                if (result.data.hasMore) {
                    shouldShowMoreButton = true;
                    addMoreCommentButton(rightcommentList, currentPageNum);
                } else {
                    shouldShowMoreButton = false;
                }

            },
            error: function (error) {
                console.error('全部评论获取失败', error);
            }
        });
    };
    commentIcon.addEventListener('click', showHandler);
    if (ViewOtherComments) {
        ViewOtherComments.addEventListener('click', showHandler);

    }

}

//评论的无限滚动
let isLoading = false; // 防止重复加载的标志
function loadMoreComments(postId, currentPageNUm) {
    if (isLoading) return;
    isLoading = true;
    currentPageNUm += 1;
    $.ajax({
        url: `/post/selectComment/${postId}/${currentPageNUm}`,
        type: 'GET',
        data: {
            pageNum: currentPageNUm,
            postId: postId
        },
        success: function (result) {
            console.log(result);
            console.log(result.data.hasMore);
            // 移除按钮
            const moreCommentButton = document.getElementById('more-comment-btn');
            if (moreCommentButton) {
                console.log("获取到按钮");
                moreCommentButton.remove();
            }

            result.data.comments.forEach(function (comment) {
                rightcommentList.innerHTML += createCommentHtml(comment, userId);
            });
            if (result.data.hasMore) {
                shouldShowMoreButton = true;
                addMoreCommentButton(rightcommentList, currentPageNUm);
            } else {
                shouldShowMoreButton = false;
                console.log("暂无更多评论");
                const noMoreComments = document.createElement('div');
                noMoreComments.classList.add('noMoreComments');
                noMoreComments.textContent = "暂无更多评论";
                rightcommentList.appendChild(noMoreComments);
            }
            // 重新绑定删除和点赞事件
            bindDeleteCommentEvents();
            LikeCommentEvents();
            setCommentLikeStatus();
            isLoading = false;
        },
        error: function (error) {
            console.error('加载更多评论失败', error);
            isLoading = false;
        }
    });
}
//添加"显示更多评论"按钮
function addMoreCommentButton(commentListElement, currentPageNum) {
    console.log(shouldShowMoreButton);
    if (!shouldShowMoreButton) return;
    console.log("要显示按钮了");
    const moreCommentButton = document.createElement('button');
    moreCommentButton.type = 'button'; // 关键修改：指定按钮类型
    moreCommentButton.id = 'more-comment-btn'; // 添加唯一id
    moreCommentButton.textContent = "显示更多评论";
    moreCommentButton.classList.add('more-comment-button');
    moreCommentButton.addEventListener('click', function (event) {
        event.preventDefault(); // 阻止默认事件
        console.log("元素默认行为已取消");
        // this.remove();
        // const currentPageNum = currentPageNum;
        // moreCommentButton.remove();
        // currentPageNum++;
        loadMoreComments(postId, currentPageNum);
    });
    commentListElement.appendChild(moreCommentButton);
    // commentListElement.dataset.pageNum = parseInt(commentListElement.dataset.pageNum || 1) + 1;
}

//点击"评论"将评论的内容渲染到页面上
//1.主评论
function handleCommentSubmit() {
    //获取评论列表
    const commentLists = document.querySelectorAll('.comment-list');
    //获取主评论的评论按钮
    const commentButtons = document.querySelectorAll('.commonCommentSubmit');
    //为两个评论提交按钮绑定相同事件
    commentButtons.forEach(button => {
        button.addEventListener('click', function () {
            //找到所点击的评论按钮所对应的输入框
            const input = this.closest('.Comments-bottom-input').querySelector('.commonCommentInput');
            const commentText = input.value;
            console.log(commentText.length);
            if (commentText.length == 0) {
                button.style.disabled = 'true';
                return;
            }
            // 发送AJAX请求
            $.ajax({
                url: '/NewsController/comment',
                type: 'POST',
                data: {
                    content: commentText,
                    postId: postId,
                },
                success: function (result) {
                    console.log(result);
                    if (result.message == "请先登录")
                        return;
                    //清空输入框
                    input.value = '';
                    // // 重新绑定删除和点赞按钮事件
                    // bindDeleteCommentEvents();
                    // LikeCommentEvents();

                    currentPageNum = 1;
                    // 刷新两侧评论列表
                    updateCommentLists(result.data);
                    // 更新评论数量
                    updateCommentCount(result.data.allComments.length);
                    if (rightNoComments && noComments) {
                        rightNoComments.style.display = 'none';
                        noComments.style.display = 'none';
                        ViewOtherComments.style.display = 'block';
                    }

                },
                error: function (error) {
                    console.error('评论提交失败', error);
                    alert('评论提交失败，请检查输入并重试');
                }
            });
        })
    })
}
if (isLoggedIn) {
    handleCommentSubmit();
}
// 下方和右边评论列表更新函数
function updateCommentLists(data) {
    const homeCommentList = document.querySelector('.comment-list');
    const rightCommentList = document.querySelector('.rightCommentList');

    // 清空原有内容（避免静态与动态节点混合）
    homeCommentList.innerHTML = '';
    rightCommentList.innerHTML = '';

    // 渲染首页评论（前4条）
    data.fourComments.forEach(comment => {
        homeCommentList.innerHTML += createCommentHtml(comment, userId);
    });

    // 渲染右侧全部评论
    // data.allComments.forEach(comment => {
    //     rightCommentList.innerHTML += createCommentHtml(comment, userId);
    // });
    // 右侧：显示当前页的评论（根据 currentPageNum 和 PAGE_SIZE 计算）
    const startIndex = (currentPageNum - 1) * PAGE_SIZE;
    const endIndex = currentPageNum * PAGE_SIZE;
    const currentPageComments = data.allComments.slice(startIndex, endIndex);
    let commentRenderedCount = 0; // 新增变量，记录已渲染的评论数量
    currentPageComments.forEach(comment => {
        rightCommentList.innerHTML += createCommentHtml(comment, userId);
        commentRenderedCount++;
        console.log(comment.likeCount);
    });
    //  更新分页状态：判断是否需要显示“更多”按钮
    shouldShowMoreButton = data.allComments.length > commentRenderedCount; // 总评论数 > 当前页结束索引则显示按钮

    // 移除旧按钮并重新添加（如有需要）
    const moreCommentButton = document.getElementById('more-comment-btn');
    if (moreCommentButton) moreCommentButton.remove();
    if (shouldShowMoreButton) {
        addMoreCommentButton(rightCommentList, currentPageNum);
    } else {
        // 显示无更多评论提示
        const noMoreComments = document.createElement('div');
        noMoreComments.classList.add('noMoreComments');
        noMoreComments.textContent = "暂无更多评论";
        rightCommentList.appendChild(noMoreComments);
    }

    // 重新绑定删除和点赞事件
    bindDeleteCommentEvents();
    LikeCommentEvents();
    setCommentLikeStatus();


}
function getCommentStatus(commentId, callback) {
    $.ajax({
        url: '/NewsController/commentstatus',
        type: 'GET',
        data: {
            commentId: commentId
        },
        success: function (result) {
            callback(result.data);
        },
        error: function (error) {
            console.error('获取评论状态失败', error);
            callback({});
        }
    });
}
// 创建评论 HTML 模板函数
function createCommentHtml(comment, userId) {
    const isCurrentUser = comment.userId === userId;
    // console.log(comment.likeCount);
    const deleteButton = isCurrentUser ?
        '<div class="delete-myComment"><i class="iconfont icon-quxiao"></i></div>' :
        '<div></div>'; // 占位符

    return `
    <div class="comment-item" data-comment-id="${comment.commentId}">
        <img src="${comment.avatar}" alt="用户头像" class="user-avatar" onclick="otherUserPage('${comment.userId}')">
        <div class="comment-header">
            <span class="user-name">${comment.userName}</span>
            <i class="iconfont icon-dianzan"></i>
            <span class="like-count">${comment.likeCount}</span>
        </div>
        <div class="comment-body">
            <p>${comment.content}</p>
        </div>
        <div class="comment-footer">
            <div>
                <span class="reply-button">回复</span>
                <span class="comment-time">${comment.createdTime}</span>
            </div>
            ${deleteButton}
        </div>
    </div>
    `;
}
function setCommentLikeStatus() {
    const commentItems = document.querySelectorAll('.comment-item');
    commentItems.forEach(item => {
        const commentId = item.dataset.commentId;
        getCommentStatus(commentId, function (status) {
            const likeIcon = item.querySelector('.icon-dianzan');
            const likeCount = item.querySelector('.like-count');
            const likeStatus = status.likeStatus;
            if (likeStatus === 1) {
                likeIcon.style.color = 'red';
                likeCount.style.color = 'red';
            } else {
                likeIcon.style.color = '';
                likeCount.style.color = '';

            }
        });
    });
}
// 更新评论数量函数
function updateCommentCount(count) {
    const commentCounts = document.querySelectorAll('.comment-count');
    console.log(commentCounts);
    commentCounts.forEach(countElement => {
        countElement.textContent = count;
    });

}

//关闭弹窗
const confirmPopup = document.querySelector('.confirm-popup');
const deleteCloseButton = document.querySelector('.delete-close-button');
console.log(deleteCloseButton)
const cancelButton = document.querySelector('.cancel-button');
const confirmText = document.querySelector('.confirm-text');
const confirmButton = document.querySelector('.confirm-button');

function closePopup() {
    console.log("已关闭")
    confirmPopup.classList.add('closing');
    setTimeout(() => {
        confirmPopup.classList.remove('active');
        confirmPopup.classList.remove('closing');
    }, 300); // 动画时长为 0.5s，所以这里设置 500ms
}
//删除自己所发表评论
//删除按钮的弹窗(如果不封装成函数的话,可能会出现在ajax动态添加元素之前DOM获取的代码就执行了,会导致获取不到元素,比如那个叉号图标)
function bindDeleteCommentEvents() {

    const commentLists = document.querySelectorAll('.comment-list');
    // if (!commentLists) return;
    // 绑定到父容器，监听子元素的点击事件
    commentLists.forEach(commentList => {
        commentList.addEventListener('click', function (event) {
            // 检查点击事件是否发生在 .delete-myComment 元素上
            const deleteMyComment = event.target.closest('.delete-myComment');
            // console.log(deleteMyComment)
            if (deleteMyComment) {
                // console.log("以点击删除按钮");
                const commentItem = deleteMyComment.closest('.comment-item');
                const currentCommentId = commentItem.dataset.commentId;
                console.log('要删除的评论ID:', currentCommentId);

                // 处理删除逻辑
                confirmPopup.classList.add('active');
                confirmText.textContent = "确定删除此评论吗?";

                // 在确认按钮的点击事件中使用commentId
                confirmButton.onclick = function () {
                    deleteComment(currentCommentId); // 调用删除函数
                    closePopup(); // 关闭弹窗
                };
                deleteCloseButton.addEventListener('click', closePopup);
                cancelButton.addEventListener('click', closePopup);

            }
        });
    })

}
//删除评论函数
function deleteComment(commentId) {
    console.log('commentId的数据类型:', typeof commentId);//"string"
    $.ajax({
        url: `/NewsController/deleteComment/${commentId}`,
        type: "POST",
        data: {
            commentId: commentId
        },
        success: function (result) {
            console.log(result);
            //移除评论元素
            const commentElement = document.querySelector(`.comment-item[data-comment-id="${commentId}"]`);
            if (commentElement) {
                commentElement.remove();
            } else {
                console.log('未找到要删除的评论元素');
            }
            //删除操作之后再次更新评论列表,因为后端这个接口删除成功后没有返回最新的评论列表数据,所以这里可以再次调用最开始渲染评论的函数
            loadInitialComments(postId);
        },
        error: function (error) {
            console.log(error);

        }
    })
}
function LikeCommentEvents() {

    const commentLists = document.querySelectorAll('.comment-list');
    // 绑定到父容器，监听子元素的点击事件
    commentLists.forEach(commentList => {
        commentList.addEventListener('click', function (event) {
            // 检查点击事件是否发生在 .delete-myComment 元素上
            const iconLike = event.target.closest('.icon-dianzan');
            // console.log(iconLike);
            if (iconLike) {
                console.log("以点击点赞按钮");
                const commentItem = iconLike.closest('.comment-item');
                const currentCommentId = commentItem.dataset.commentId;
                console.log('要点赞的评论ID:', currentCommentId);
                likeComment(currentCommentId);
            }
        });
    })

}
function likeComment(commentId) {
    if (isLoggedIn) {
        const currentlikeCount = document.querySelector(
            `.comment-item[data-comment-id="${commentId}"] .like-count`
        ).textContent;
        $.ajax({
            url: "/NewsController/likecomment",
            type: "POST",
            data: {
                commentId: commentId
            },
            success: function (result) {
                console.log(result);
                const likeCountElements = document.querySelectorAll(
                    `.comment-item[data-comment-id="${commentId}"] .like-count`
                );
                console.log(likeCountElements);
                const iconLikes = document.querySelectorAll(
                    `.comment-item[data-comment-id="${commentId}"] .icon-dianzan`
                );
                // console.log(iconLikes);
                console.log(currentlikeCount);
                if (likeCountElements && iconLikes) {
                    const newLikeCount = result.data;
                    console.log(newLikeCount);
                    // const prevLikeCount = parseInt(currentlikeCount);
                    if (newLikeCount > currentlikeCount) {
                        likeCountElements.forEach(likeCountElement => {
                            likeCountElement.style.color = 'red';
                        })
                        iconLikes.forEach(iconLike => {
                            iconLike.style.color = 'red';
                        })
                    } else {
                        likeCountElements.forEach(likeCountElement => {
                            likeCountElement.style.color = '';
                        })
                        iconLikes.forEach(iconLike => {
                            iconLike.style.color = '';
                        })
                    }
                    likeCountElements.forEach(likeCountElement => {
                        likeCountElement.textContent = newLikeCount;
                    })
                }


            }
        })
    } else {
        showAlert("请先登录", 'red');
    }


}
